package org.example.service;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.util.Properties;

@Intercepts({
    @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
    @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
})
public class SqlPrintInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 获取执行参数
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        Object parameter = invocation.getArgs()[1];
        
        // 获取BoundSql对象
        BoundSql boundSql = mappedStatement.getBoundSql(parameter);
        
        // 获取SQL语句和参数
        String sql = boundSql.getSql();
        Object parameterObject = boundSql.getParameterObject();
        
        // 打印SQL信息
        System.out.println("============== SQL START ==============");
        System.out.println("SQL ID: " + mappedStatement.getId());
        System.out.println("SQL: " + formatSql(sql));
        System.out.println("Parameters: " + parameterObject);
        System.out.println("============== SQL END ==============");
        
        // 继续执行原始方法
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        // 可接收配置参数
    }
    
    /**
     * 格式化SQL语句
     * @param sql 原始SQL
     * @return 格式化后的SQL
     */
    private String formatSql(String sql) {
        return sql.replaceAll("\\s+", " ").trim();
    }
}
